package com.bsoft.gol.editor.dao;


import ctd.persistence.annotation.DAOMethod;
import ctd.persistence.annotation.DAOParam;
import ctd.persistence.support.hibernate.template.AbstractHibernateStatelessResultAction;
import ctd.persistence.support.hibernate.template.HibernateSessionTemplate;
import ctd.persistence.support.hibernate.template.HibernateStatelessResultAction;
import com.bsoft.gol.editor.editor.EditorAnswer;
import org.hibernate.Query;
import org.hibernate.StatelessSession;
import org.hibernate.criterion.CriteriaSpecification;
import com.bsoft.gol.editor.utils.CommonUtils;

import java.util.List;
import java.util.Map;

/**
 * Created by Sangs on 2020/4/3.
 */
public abstract class EditorAnswerDAO extends ctd.persistence.support.hibernate.HibernateSupportDelegateDAO<EditorAnswer> {

    public EditorAnswerDAO() {
        this.setKeyField("answerId");
    }

    @DAOMethod(sql = "from EditorAnswer where questionnaireId=:questionnaireId and userInfoId=:userInfoId and titleId=:titleId")
    public abstract EditorAnswer getEditorAnswerById(@DAOParam("questionnaireId") String questionnaireId,@DAOParam("userInfoId") String userInfoId,@DAOParam("titleId") String titleId);

    @DAOMethod(sql = "update EditorAnswer set answeAbnormal= 1 where userInfoId =:userInfoId ")
    public abstract void updateEditorAnswerIfAbnormal(@DAOParam("userInfoId") String userInfoId);

    @DAOMethod(sql = "delete from EditorAnswer where userInfoId = :userInfoId")
    public abstract void removeByUserInfoId(@DAOParam("userInfoId") String userInfoId);

    @DAOMethod(sql = " from  EditorAnswer  where questionnaire_id =:questionnaireId and title_id =:titleId")
    public abstract List<EditorAnswer> queryEditorQuestionnaireAnswerList(@DAOParam("questionnaireId")String questionnaireId, @DAOParam("titleId")String titleId);

    public Long queryEditorAnswerCount(final String questionnaireId,final String titleId) {
        HibernateStatelessResultAction<Long> action = new AbstractHibernateStatelessResultAction<Long>() {
            @Override
            public void execute(StatelessSession ss) {
                StringBuilder sqlBuilder = new StringBuilder();
                sqlBuilder.append("select count(1) countValue from editor_answer a where 1=1");
                sqlBuilder.append(" and  questionnaire_id  =  '"+questionnaireId+"'");
                sqlBuilder.append(" and  title_id  =  '"+titleId+"'");
                Query query = ss.createSQLQuery(sqlBuilder.toString());
                query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);

                List<Map> dbList = query.list();

                if (CommonUtils.isNotEmpty(dbList)) {
                    setResult(Long.valueOf(String.valueOf(dbList.get(0).get("countValue"))));
                } else {
                    setResult(0L);
                }
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }




}